package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.DepartmentMapper;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.qo.EmployeeQo;
import cn.wolfcode.rbac.qo.QueryObject;
import cn.wolfcode.rbac.service.IDepartmentService;
import cn.wolfcode.rbac.web.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

import static cn.wolfcode.rbac.common.RedisKeyPrefix.CACHE_PREFIX;

/**
 * 部门业务
 */
@Service
@Transactional
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public PageInfo<Department> list(QueryObject qo) {
        //设置分页
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        //查询所有部门信息
        List<Department> departments = departmentMapper.selectAll();
        //把查询的部门信息存到PageInfo中即可实现分页
        return new PageInfo(departments);
    }

    @Override
    public void delete(Long id) {
        //删除部门id删除部门信息,注意：判断是否有员工是该部门
        //根据部门id查询员工信息
        EmployeeQo employeeQo = new EmployeeQo();
        employeeQo.setDeptId(id);
        List<Employee> employees = employeeMapper.selectAll(employeeQo);
        if(!employees.isEmpty()){
            throw new BusinessException("有员工是该部门,删除失败");
        }
        //如果该部门没有员工关联则可以删除
        int result = departmentMapper.deleteByPrimaryKey(id);
        if(result == 0){
            throw new BusinessException("删除失败");
        }
    }

    @Override
    public void save(Department department) {
        int result = departmentMapper.insert(department);
        if(result == 0){
            throw new BusinessException("部门信息保存失败");
        }
    }

    @Override
    public void update(Department department) {
        int result = departmentMapper.updateByPrimaryKey(department);
        if(result == 0){
            throw new BusinessException("部门信息更新失败");
        }
    }

    @Override
    public Department get(Long id) {
        Department department = departmentMapper.selectByPrimaryKey(id);
        if(department == null){
            throw new BusinessException("没有该部门信息");
        }
        return department;
    }

    @Override
    public List<Department> listAll() {
        return departmentMapper.selectAll();
    }


}
